package com.jilian.powerstation.modul.natives;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jilian.powerstation.MyApplication;
import com.jilian.powerstation.R;
import com.jilian.powerstation.base.BaseActivity;
import com.jilian.powerstation.common.dto.AdvanceSettingDto;
import com.jilian.powerstation.common.dto.BaseSettingDto;
import com.jilian.powerstation.common.event.MessageEvent;
import com.jilian.powerstation.dialog.nicedialog.BaseNiceDialog;
import com.jilian.powerstation.dialog.nicedialog.NiceDialog;
import com.jilian.powerstation.dialog.nicedialog.ViewConvertListener;
import com.jilian.powerstation.dialog.nicedialog.ViewHolder;
import com.jilian.powerstation.http.SocketConfig;
import com.jilian.powerstation.http.SocketUtils;
import com.jilian.powerstation.utils.DataUtils;
import com.jilian.powerstation.utils.EmptyUtils;
import com.jilian.powerstation.utils.NumberUtils;
import com.jilian.powerstation.utils.OnePointLengthFilter;
import com.jilian.powerstation.utils.PinziDialogUtils;
import com.jilian.powerstation.utils.RxTimerUtil;
import com.jilian.powerstation.utils.ToastUitl;
import com.jilian.powerstation.utils.TwoPointLengthFilter;
import com.jilian.powerstation.utils.rxjava.RxBus;
import com.jilian.powerstation.utils.rxjava.RxBusBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.List;

import io.reactivex.functions.Consumer;

public class AdvancedSettingActivity extends BaseActivity {
    private EditText tv01;
    private EditText tv02;
    private EditText tv03;
    private LinearLayout llOne;
    private TextView tv04;
    private EditText tv05;
    private LinearLayout llTwo;
    private TextView tv06;
    private LinearLayout llThree;
    private TextView tv07;
    private RelativeLayout llFour;
    private EditText tv08;
    private EditText tv09;
    private EditText tv10;
    private EditText tv11;
    private EditText tv12;
    private EditText tv13;
    private EditText tv14;
    private EditText tv15;
    private EditText tv16;
    private TextView tvReset;

    @Override
    protected void createViewModel() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_advancedsetting;
    }

    @Override
    public void initView() {
        setNormalTitle("Advanced setting", v -> finish());
        setrightTitle("Save", "#3298db", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveAdvanceSetting();
            }
        });

        tv01 = (EditText) findViewById(R.id.tv_01);
        tv02 = (EditText) findViewById(R.id.tv_02);
        tv03 = (EditText) findViewById(R.id.tv_03);
        llOne = (LinearLayout) findViewById(R.id.ll_one);
        tv04 = (TextView) findViewById(R.id.tv_04);
        tv05 = (EditText) findViewById(R.id.tv_05);
        llTwo = (LinearLayout) findViewById(R.id.ll_two);
        tv06 = (TextView) findViewById(R.id.tv_06);
        llThree = (LinearLayout) findViewById(R.id.ll_three);
        tv07 = (TextView) findViewById(R.id.tv_07);
        llFour = (RelativeLayout) findViewById(R.id.ll_four);
        tv08 = (EditText) findViewById(R.id.tv_08);
        tv09 = (EditText) findViewById(R.id.tv_09);
        tv10 = (EditText) findViewById(R.id.tv_10);
        tv11 = (EditText) findViewById(R.id.tv_11);
        tv12 = (EditText) findViewById(R.id.tv_12);
        tv13 = (EditText) findViewById(R.id.tv_13);
        tv14 = (EditText) findViewById(R.id.tv_14);
        tv15 = (EditText) findViewById(R.id.tv_15);
        tv16 = (EditText) findViewById(R.id.tv_16);
        tvReset = (TextView) findViewById(R.id.tv_reset);
        tv08.setFilters(new InputFilter[]{new TwoPointLengthFilter()});
        tv09.setFilters(new InputFilter[]{new TwoPointLengthFilter()});
        tv10.setFilters(new InputFilter[]{new TwoPointLengthFilter()});

        tv11.setFilters(new InputFilter[]{new TwoPointLengthFilter()});
        tv12.setFilters(new InputFilter[]{new TwoPointLengthFilter()});
    }


    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        getLoadingDialog().show();
        sandMessage();

    }
    private boolean isFront = false;
    @Override
    protected void onResume() {
        super.onResume();
        isFront = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isFront = false;

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        MyApplication.removeActivity(this);
        if (rxBus != null) {
            rxBus.unSubscribe(this);
            rxBus = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        // 当按下返回键时所执行的命令
        if (keyCode == KeyEvent.KEYCODE_BACK&&isChange) {
            // 此处写你按返回键之后要执行的事件的逻辑
            showLeaveDialog();
            return false;
        }
        return super.onKeyDown(keyCode, event);

    }
    private boolean isChange;
    private void showConfirmDialog() {
        Dialog dialog = PinziDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_confirm);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        TextView tvNo = (TextView) dialog.findViewById(R.id.tv_no);
        TextView tvOk = (TextView) dialog.findViewById(R.id.tv_ok);
        tvTitle.setText("tips");
        tvContent.setText("Whether to confirm the factory reset");

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUitl.showImageToastTips("resetting...");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e("基础设置配置命令重置", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.resetSetting()));
                                SocketUtils.sendSerialPort(SocketConfig.resetSetting());
                            }
                        }).start();
                    }
                }, 10);
                sandMessage30();
                dialog.dismiss();

            }
        });
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();


    }
    private void sandMessage30() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("基础设置查询命令", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.getSetting()));
                        SocketUtils.sendSerialPort(SocketConfig.getSetting());
                    }
                }).start();

            }
        }, 3000);
    }
    @Override
    public void initListener() {
        tvReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showConfirmDialog();


            }
        });
        tv01.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });
        tv02.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv03.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv05.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv08.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv09.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv10.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv11.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv12.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv13.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv14.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv15.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });

        tv16.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isChange = true;
            }
        });








        findViewById(R.id.v_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isChange){
                    showLeaveDialog();
                }
                else{
                    finish();
                }
            }
        });
        //安规标准
        tv06.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSatetyStandardssDialog();
            }
        });
        //电网电压响应设置
        tv07.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AdvancedSettingActivity.this, VoltResponseModeActivity.class));
            }
        });
        //手动操作
        tv04.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AdvancedSettingActivity.this, ManualOperationActivity.class));

            }
        });
    }


    /**
     * 安规标准
     */
    private void showSatetyStandardssDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_satety_standards_select)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);


                        TextView btnOne = (TextView) holder.getView(R.id.btn_one);
                        TextView btnTwo = (TextView) holder.getView(R.id.btn_two);
                        TextView btnThree = (TextView) holder.getView(R.id.btn_three);
                        TextView btnFour = (TextView) holder.getView(R.id.btn_four);
                        TextView btnCancel = (TextView) holder.getView(R.id.btn_cancel);

                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        btnOne.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                tv06.setText(btnOne.getText().toString());
                                type = 0;

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Log.e("基础设置配置命令", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.selectCountry(type)));
                                                SocketUtils.sendSerialPort(SocketConfig.selectCountry(type));
                                            }
                                        }).start();

                                    }
                                }, 10);


                            }
                        });
                        btnTwo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                type = 1;
                                dialog.dismiss();
                                tv06.setText(btnTwo.getText().toString());
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Log.e("基础设置配置命令", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.selectCountry(type)));
                                                SocketUtils.sendSerialPort(SocketConfig.selectCountry(type));
                                            }
                                        }).start();

                                    }
                                }, 10);


                            }
                        });

                        btnThree.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                type = 2;
                                tv06.setText(btnThree.getText().toString());

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Log.e("基础设置配置命令", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.selectCountry(type)));
                                                SocketUtils.sendSerialPort(SocketConfig.selectCountry(type));
                                            }
                                        }).start();

                                    }
                                }, 10);


                            }
                        });

                        btnFour.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();
                                tv06.setText(btnFour.getText().toString());
                                type = 3;

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Log.e("基础设置配置命令", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.selectCountry(type)));
                                                SocketUtils.sendSerialPort(SocketConfig.selectCountry(type));
                                            }
                                        }).start();

                                    }
                                }, 10);


                            }
                        });


                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    //熊浪添加RxBus工具类，页面销毁时需要取消注册，否则会有内存泄漏
    private RxBus rxBus;
    private boolean isGetData;
    private String errors[] = new String[]{"Configuration is complete", "After finishing the configuration, power down and restart the device.", "After finishing the configuration, restart in operating mode.", "Disable services for system configuration", "Unable to configure in transparent transmission upgrade", "Parameter out of range", "Parameter ID is not defined", "Parameter conflict, please check"};
    private String tip;



    /**
     * contentByte[31]=(byte)0xA1;//电池最大充电电压（DCDC） 1V
     * contentByte[32]=(byte)0xA2;//电池最大充电电流（DCDC） 1A
     * contentByte[33]=(byte)0xA4;//电池最大放电电流（DCDC） 1A
     * contentByte[34]=(byte)0xB1;//数据上传间隔 1MS
     * contentByte[35]=(byte)0xD2;//安规标准0:澳洲 1：新西兰 2：德国 3：预留
     * contentByte[36]=(byte)0xBE;//电网电压响应模式  0: 电压功率响应模式 1: 电压无功响应模式 2: 固定功率因数 无功响应模式 3: 特征功率因数曲线响应模式
     * contentByte[37]=(byte)0xBB;//并网功率因素 0.01
     * contentByte[38]=(byte)0xCA;//并网充电功率上升梯度 0.01%
     * contentByte[39]=(byte)0xCF;//并网放电功率上升梯度 0.01%
     * contentByte[40]=(byte)0xCB;//梯度调控过频点  0.01HZ
     * contentByte[41]=(byte)0xCC;//梯度调控欠频点  0.01HZ
     * contentByte[42]=(byte)0xC7;//电压响应参考值V2 0.1V
     * contentByte[43]=(byte)0xC8;//电压响应参考值V3 0.1V
     * contentByte[44]=(byte)0xC9;//电压响应参考值V4 0.1V
     * contentByte[45]=(byte)0xCD;//电网电压10min平均最大值 0.1V
     */
    private String F = "";
    private int type = 0;

    private void initAdvanceSetting(AdvanceSettingDto settingDto) {

        Log.e(TAG, "高级设置查询命令: " + settingDto.toString());
        isGetData = true;
        //电池最大充电电压
        tv01.setText(settingDto.getA() + "");
        //电池最大充电电流（DCDC） 1A
        tv02.setText(settingDto.getB() + "");
        //电池最大放电电流（DCDC） 1A
        tv03.setText(settingDto.getC() + "");
        //数据上传间隔（DCDC） 1A
        tv05.setText(settingDto.getD() + "");
        //安规标准0:澳洲 1：新西兰 2：德国 3：预留
        if (settingDto.getE() == 0) {
            type = 0;
            tv06.setText("Australia");
        }
        if (settingDto.getE() == 1) {
            type = 1;
            tv06.setText("New Zealand");
        }
        if (settingDto.getE() == 2) {
            type = 2;
            tv06.setText("Germany");
        }
        if (settingDto.getE() == 3) {
            type = 3;
            tv06.setText("The reserved");
        }
        //0: 电压功率响应模式 1: 电压无功响应模式 2: 固定功率因数 无功响应模式 3: 特征功率因数曲线响应模式
        if (settingDto.getF() == 0) {
            F = "电压功率响应模式";
            //tv07.setText("电压功率响应模式");
        }
        if (settingDto.getF() == 1) {
            F = "电压无功响应模式";
            // tv07.setText("电压无功响应模式");
        }
        if (settingDto.getF() == 2) {
            F = "固定功率因数无功响应模式";
            // tv07.setText("固定功率因数无功响应模式");
        }
        if (settingDto.getF() == 3) {
            F = "特征功率因数曲线响应模式";
            //tv07.setText("特征功率因数曲线响应模式");
        }

        //并网功率因素
        tv08.setText(NumberUtils.forMatNumber(settingDto.getG() * 0.01));

        //并网充电功率上升梯度
        tv09.setText(NumberUtils.forMatNumber(settingDto.getH() * 0.01));

        //并网放电功率上升梯度
        tv10.setText(NumberUtils.forMatNumber(settingDto.getI() * 0.01));

        //梯度调控过频点
        tv11.setText(NumberUtils.forNormalMatNumber(settingDto.getJ() * 0.01));

        //梯度调控欠频点
        tv12.setText(NumberUtils.forNormalMatNumber(settingDto.getK() * 0.01));


        //电压响应参考值V2
        tv13.setText(settingDto.getL() + "");

        //电压响应参考值V3
        tv14.setText(settingDto.getM() + "");

        //电压响应参考值V4
        tv15.setText(settingDto.getN() + "");

        //电网电压10min平均最大值 0.1V
        tv16.setText(settingDto.getO() + "");


        isChange = false;

    }

    private void sandMessage() {
//        getLoadingDialog().show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("高级设置查询命令", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.getAdvanceSetting()));
                        SocketUtils.sendSerialPort(SocketConfig.getAdvanceSetting());
                    }
                }).start();

            }
        }, 10);
    }

    private int e = 0;

    private boolean isSetting;
    /**
     * 保存设置
     */
    private void saveAdvanceSetting() {
        if (TextUtils.isEmpty(tv01.getText().toString())
                || TextUtils.isEmpty(tv02.getText().toString())
                || TextUtils.isEmpty(tv03.getText().toString())
                || TextUtils.isEmpty(tv05.getText().toString())
                || TextUtils.isEmpty(tv06.getText().toString())
//                ||TextUtils.isEmpty(tv07.getText().toString())
                || TextUtils.isEmpty(tv08.getText().toString())
                || TextUtils.isEmpty(tv09.getText().toString())
                || TextUtils.isEmpty(tv10.getText().toString())
                || TextUtils.isEmpty(tv11.getText().toString())
                || TextUtils.isEmpty(tv12.getText().toString())
                || TextUtils.isEmpty(tv13.getText().toString())
                || TextUtils.isEmpty(tv14.getText().toString())
                || TextUtils.isEmpty(tv15.getText().toString())
                || TextUtils.isEmpty(tv16.getText().toString())
        ) {
            ToastUitl.showImageToastTips("Data cannot be empty");
            return;


        }
        int a = Integer.parseInt(tv01.getText().toString());
        int b = Integer.parseInt(tv02.getText().toString());
        int c = Integer.parseInt(tv03.getText().toString());
        int d = Integer.parseInt(tv05.getText().toString());


        //安规标准0:澳洲 1：新西兰 2：德国 3：预留

        if (tv06.getText().toString().equals("Australia")) {
            e = 0;
        }
        if (tv06.getText().toString().equals("New Zealand")) {
            e = 1;
        }
        if (tv06.getText().toString().equals("America")) {
            e = 2;
        }
        if (tv06.getText().toString().equals("The reserved")) {
            e = 3;
        }


        int g = (int) (Double.parseDouble(tv08.getText().toString()) * 100);
        int h = (int) ((Double.parseDouble(tv09.getText().toString()) * 100));
        int i = (int) ((Double.parseDouble(tv10.getText().toString()) * 100));
        int j = (int) (Double.parseDouble(tv11.getText().toString()) * 100);
        int k = (int) (Double.parseDouble(tv12.getText().toString()) * 100);


        int l = (int) Double.parseDouble(tv13.getText().toString());
        int m = (int) Double.parseDouble(tv14.getText().toString());
        int n = (int) Double.parseDouble(tv15.getText().toString());
        int o = (int) Double.parseDouble(tv16.getText().toString());
        isSetting = true;
        RxTimerUtil.cancel();
        RxTimerUtil.timer(16000, new RxTimerUtil.IRxNext() {
            @Override
            public void doNext() {
                if(isSetting){
                    getLoadingDialog().dismiss();
                    ToastUitl.showImageToastTips("Time timeout");
                }
            }
        });

        getLoadingDialog().showDialog();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("基础设置配置命令", "发送的16进制指令: " + DataUtils.hexBytesToString(SocketConfig.advanceSetting(a, b, c, d, e,  g, h, i, j, k, l, m, n, o)));
                        SocketUtils.sendSerialPort(SocketConfig.advanceSetting(a, b, c, d, e, g, h, i, j, k, l, m, n, o));
                    }
                }).start();

            }
        }, 10);


    }





    /**
     * 退出登录对话框
     */
    private void showTipsDialog(String msg) {
        isChange = false;
        Dialog dialog = PinziDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_confirm);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        TextView tvNo = (TextView) dialog.findViewById(R.id.tv_no);
        TextView tvOk = (TextView) dialog.findViewById(R.id.tv_ok);
        tvTitle.setText("tips");
        tvContent.setText(msg);
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

            }
        });
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();


    }


    /**
     * //监听外来是否要去成功的界面
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        /* Do something */
        if (EmptyUtils.isNotEmpty(event)
                && EmptyUtils.isNotEmpty(event.getSendMessage())

        ) {

            initSenMessage(event.getSendMessage());
        }
    }

    private void initSenMessage(RxBusBean.SendMessage sendMessage) {
        if(!isFront){
            return;
        }

        /**
         *         contentByte[31]=(byte)0xA1;//电池最大充电电压（DCDC）
         *         contentByte[32]=(byte)0xA2;//电池最大充电电流（DCDC）
         *         contentByte[33]=(byte)0xA4;//电池最大放电电流（DCDC）
         *         contentByte[34]=(byte)0xB1;//数据上传间隔
         *         contentByte[35]=(byte)0xD2;//安规标准0:澳洲 1：新西兰 2：德国 3：预留
         *         contentByte[36]=(byte)0xBE;//电网电压响应模式  0: 电压功率响应模式 1: 电压无功响应模式 2: 固定功率因数 无功响应模式 3: 特征功率因数曲线响应模式
         *         contentByte[37]=(byte)0xBB;//并网功率因素
         *         contentByte[38]=(byte)0xCA;//并网充电功率上升梯度 0.01%
         *         contentByte[39]=(byte)0xCF;//并网放电功率上升梯度 0.01%
         *         contentByte[40]=(byte)0xCB;//梯度调控过频点  0.01HZ
         *         contentByte[41]=(byte)0xCC;//梯度调控欠频点  0.01HZ
         *         contentByte[42]=(byte)0xC7;//电压响应参考值V2 0.1V
         *         contentByte[43]=(byte)0xC8;//电压响应参考值V3 0.1V
         *         contentByte[44]=(byte)0xC9;//电压响应参考值V4 0.1V
         *         contentByte[45]=(byte)0xCD;//电网电压10min平均最大值 0.1V
         */
        //  查询命令
        if (sendMessage != null && sendMessage.readContent[2] == SocketConfig.SEARCH) {

            try {
                getLoadingDialog().dismiss();
                Log.e("高级设置查询命令", "我接收到了查询命令的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
                Log.e("高级设置查询命令", "接受到的最原始的数据:" + DataUtils.ByteArrToHex(sendMessage.readContent));
                Log.e("高级设置查询命令", "前六位是年月日时分秒:" + DataUtils.HexToInt(sendMessage.info[0]) + "年" + DataUtils.HexToInt(sendMessage.info[1]) + "月" + DataUtils.HexToInt(sendMessage.info[2]) + "日" + DataUtils.HexToInt(sendMessage.info[3]) + "时" + DataUtils.HexToInt(sendMessage.info[4]) + "分" + DataUtils.HexToInt(sendMessage.info[5]) + "秒");
                List<String> infoList = Arrays.asList(sendMessage.info);

                int A1Index = infoList.indexOf("A1");
                int a = DataUtils.HexToInt(sendMessage.info[A1Index+2] + sendMessage.info[A1Index+1]);
                //int a = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8]);
                Log.e("高级设置查询命令", "电池最大充电电压: " + a);

                int A2Index = infoList.indexOf("A2");
                int b= DataUtils.HexToInt(sendMessage.info[A2Index+2] + sendMessage.info[A2Index+1]);
                // int b = DataUtils.HexToInt(sendMessage.info[12] + sendMessage.info[11]);
                Log.e("高级设置查询命令", "电池最大充电电流: " + b);

                int A4Index = infoList.indexOf("A4");
                int c= DataUtils.HexToInt(sendMessage.info[A4Index+2] + sendMessage.info[A4Index+1]);
                //  int c = DataUtils.HexToInt(sendMessage.info[15] + sendMessage.info[14]);
                Log.e("高级设置查询命令", "电池最大放电电流: " + c);

                int B1Index = infoList.indexOf("B1");
                int d= DataUtils.HexToInt(sendMessage.info[B1Index+2] + sendMessage.info[B1Index+1]);
                // int d = DataUtils.HexToInt(sendMessage.info[18] + sendMessage.info[17]);
                Log.e("高级设置查询命令", "数据上传间隔: " + d);

                int D2Index = infoList.indexOf("D2");
                int e= DataUtils.HexToInt(sendMessage.info[D2Index+2] + sendMessage.info[D2Index+1]);
                // int e = DataUtils.HexToInt(sendMessage.info[21] + sendMessage.info[20]);
                Log.e("高级设置查询命令", "安规标准: " + e);

                int BEIndex = infoList.indexOf("BE");
                int f= DataUtils.HexToInt(sendMessage.info[BEIndex+2] + sendMessage.info[BEIndex+1]);
                //int f = DataUtils.HexToInt(sendMessage.info[24] + sendMessage.info[23]);
                Log.e("高级设置查询命令", "电网电压响应模式 " + f);

                int BBIndex = infoList.indexOf("BB");
                int g= DataUtils.HexToInt(sendMessage.info[BBIndex+2] + sendMessage.info[BBIndex+1]);
                //int g = DataUtils.HexToInt(sendMessage.info[27] + sendMessage.info[26]);
                Log.e("高级设置查询命令", "并网功率因素: " + g);

                int CAIndex = infoList.indexOf("CA");
                int h= DataUtils.HexToInt(sendMessage.info[CAIndex+2] + sendMessage.info[CAIndex+1]);
                // int h = DataUtils.HexToInt(sendMessage.info[30] + sendMessage.info[29]);
                Log.e("高级设置查询命令", "并网充电功率上升梯度: " + h);

                int CFIndex = infoList.indexOf("CF");
                int i= DataUtils.HexToInt(sendMessage.info[CFIndex+2] + sendMessage.info[CFIndex+1]);
                //  int i = DataUtils.HexToInt(sendMessage.info[33] + sendMessage.info[32]);
                Log.e("高级设置查询命令", "并网放电功率上升梯度: " + i);

                int CBIndex = infoList.indexOf("CB");
                int j= DataUtils.HexToInt(sendMessage.info[CBIndex+2] + sendMessage.info[CBIndex+1]);
                // int j = DataUtils.HexToInt(sendMessage.info[36] + sendMessage.info[35]);
                Log.e("高级设置查询命令", "梯度调控过频点: " + j);

                int CCIndex = infoList.indexOf("CC");
                int k= DataUtils.HexToInt(sendMessage.info[CCIndex+2] + sendMessage.info[CCIndex+1]);
                //int k = DataUtils.HexToInt(sendMessage.info[39] + sendMessage.info[38]);
                Log.e("高级设置查询命令", "梯度调控欠频点 " + k);

                int C7Index = infoList.indexOf("C7");
                int l= DataUtils.HexToInt(sendMessage.info[C7Index+2] + sendMessage.info[C7Index+1]);
                //int l = DataUtils.HexToInt(sendMessage.info[42] + sendMessage.info[41]);
                Log.e("高级设置查询命令", "电压响应参考值V2: " + l);


                int C8Index = infoList.indexOf("C8");
                int m= DataUtils.HexToInt(sendMessage.info[C8Index+2] + sendMessage.info[C8Index+1]);
                // int m = DataUtils.HexToInt(sendMessage.info[45] + sendMessage.info[44]);
                Log.e("高级设置查询命令", "电压响应参考值V3: " + m);

                int C9Index = infoList.indexOf("C9");
                int n= DataUtils.HexToInt(sendMessage.info[C9Index+2] + sendMessage.info[C9Index+1]);
                //int n = DataUtils.HexToInt(sendMessage.info[48] + sendMessage.info[47]);
                Log.e("高级设置查询命令", "电压响应参考值V4: " + n);


                int CDIndex = infoList.indexOf("CD");
                int o= DataUtils.HexToInt(sendMessage.info[CDIndex+2] + sendMessage.info[CDIndex+1]);
                // int o = DataUtils.HexToInt(sendMessage.info[51] + sendMessage.info[50]);
                Log.e("高级设置查询命令", "电网电压10min平均最大值: " + o);


                AdvanceSettingDto settingDto = new AdvanceSettingDto(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);

                initAdvanceSetting(settingDto);
            }
            catch (Exception e){
                ToastUitl.showImageToastSuccess(e.getMessage()+" - ");
            }



        }

        //  设置命令
        else if (sendMessage != null && sendMessage.readContent[2] == SocketConfig.SETTING) {
            isSetting = false;
            getLoadingDialog().dismiss();
            String hexString = DataUtils.ByteArrToHex(sendMessage.readContent);
            Log.e(TAG, "高级设置总的数据:" + hexString);
            Log.e("高级设置配置命令", "我接收到了实时信息的所有数据(已过滤传输规则中其他数据):" + Arrays.toString(sendMessage.info));
            Log.e("高级设置配置命令", "前六位是年月日时分秒:" + DataUtils.HexToInt(sendMessage.info[0]) + "年" + DataUtils.HexToInt(sendMessage.info[1]) + "月" + DataUtils.HexToInt(sendMessage.info[2]) + "日" + DataUtils.HexToInt(sendMessage.info[3]) + "时" + DataUtils.HexToInt(sendMessage.info[4]) + "分" + DataUtils.HexToInt(sendMessage.info[5]) + "秒");
            int result = DataUtils.HexToInt(sendMessage.info[6]);
            Log.e(TAG, "高级设置命令accept: " + result);

            if (result == 0 || result == 1 || result == 2 || result == 3 || result == 4 || result == 6) {
                tip = errors[result];
                showTipsDialog(tip);
            } else {
                if (result == 5)
                {
                    // BB CA CF CB CC    0.01
                    int id = DataUtils.HexToInt(sendMessage.info[7]);
                    double min;
                    double max;
                    //16进制ID
                    String idStr = DataUtils.toHexString(id);
                    if (
                            "bb".equals(idStr)
                                    || "ca".equals(idStr)
                                    || "cf".equals(idStr)
                                    || "cb".equals(idStr)
                                    || "cc".equals(idStr)) {
                        min = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8]) * 0.01;
                        max = DataUtils.HexToInt(sendMessage.info[11] + sendMessage.info[10]) * 0.01;

                    } else {
                        min = DataUtils.HexToInt(sendMessage.info[9] + sendMessage.info[8]);
                        max = DataUtils.HexToInt(sendMessage.info[11] + sendMessage.info[10]);
                    }
                    if("a1".equals(idStr)){
                        tip = "BatChrgVoltMax is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    if("a2".equals(idStr)){
                        tip = "BatChrgCurrMax is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    if("a4".equals(idStr)){
                        tip = "BatDisChrgCurrMax is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }
                    if("b1".equals(idStr)){
                        tip = "Data upload interval is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    if("bb".equals(idStr)){
                        tip = "Power factor is between ±" + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    if("ca".equals(idStr)){
                        tip = "GridChrgGrad is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    if("cf".equals(idStr)){
                        tip = "GridDisChrgGrad is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    if("cb".equals(idStr)){
                        tip = "Frestop is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    if("cc".equals(idStr)){
                        tip = "Frestop-CH is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    if("c7".equals(idStr)){
                        tip = "VoltResponse2 is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }
                    if("c8".equals(idStr)){
                        tip = "VoltResponse3 is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    if("c9".equals(idStr)){
                        tip = "VoltResponse4 is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }
                    if("cd".equals(idStr)){
                        tip = "GridVoltAvgFor10Min is between " + NumberUtils.forNormalMatNumber(min) + " and " +  NumberUtils.forNormalMatNumber(max);
                    }

                    showTipsDialog(tip);

                } else {
                    tip = "System abnormal, error code is" + sendMessage.info[6];
                    showTipsDialog(tip);
                }
            }

        }

    }

}
